//
//  YSLoginCtrl.m
//  Yueshi
//
//  Created by Northwan on 15/7/23.
//  Copyright (c) 2015年 悦食中国. All rights reserved.
//  登录

#import "YSLoginCtrl.h"
#import <TencentOpenAPI/TencentOAuth.h>
#import "YSRegisterCtrl.h"
#import "YSMineDataTool.h"
#import "YSForgetPwdCtrl.h"
#import "WeChatUserinfoRes.h"
#import "SinaClient.h"
#import "WeChatUtil.h"
#import "YSHomeDataTool.h"
#import "YSOauthLoginViewContainer.h"
#import "YSBindPhoneCtrl.h"
#import "YSCommonReqTool.h"


@interface YSLoginCtrl ()<TencentSessionDelegate>
@property (nonatomic,strong) TencentOAuth *tencentOAuth;
@property (nonatomic,strong) NSArray  *permission;
@property (weak, nonatomic) IBOutlet UITextField *phoneTextFiled;
@property (weak, nonatomic) IBOutlet UIButton *sendCodeBtn;
@property (weak, nonatomic) IBOutlet UITextField *pwdTextFiled;
//@property (strong, nonatomic)  UIImageView *bgImgView;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIView *containView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *containViewHeightConst;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *phoneTopConst;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *otherWayTopConst;
@property (strong, nonatomic) YSOauthLoginViewContainer *oauthView;

@property (weak, nonatomic) IBOutlet UIImageView *bgLoginLineLeft;
@property (weak, nonatomic) IBOutlet UILabel *otherWayLoginLabel;
@property (weak, nonatomic) IBOutlet UIImageView *bgLoginLineRight;

@property (assign, nonatomic)NSTimer *countDownTimer;
@property (assign, nonatomic)NSInteger currentTime;
@end

@implementation YSLoginCtrl

- (void)viewDidLoad {
    [super viewDidLoad];
    self.fd_prefersNavigationBarHidden = YES;
    self.currentTime = 60;
//    
//    _bgImgView = [[UIImageView alloc]initWithFrame:CGRectMake(0,0, SCREENW, SCREENH)];
//    [self.view insertSubview:_bgImgView belowSubview:self.scrollView];
//    if(SCREENH==480){// 4s 4
//        self.bgImgView.image = [UIImage imageNamed:@"bg_login_4.jpg"];
//    }else if(SCREENH==568){// 5s 5
//        self.bgImgView.image = [UIImage imageNamed:@"bg_login_5.jpg"];
//    }else if(SCREENH==667){// 6
//        self.bgImgView.image = [UIImage imageNamed:@"bg_login_6.jpg"];
//    }else if(SCREENH==736){// 6 plus
//        self.bgImgView.image = [UIImage imageNamed:@"bg_login_6p.jpg"];
//    }
    
    CGFloat topConstant = self.phoneTopConst.constant;
    CGFloat ratio = 1;
    CGFloat deviation = 0;
    if(SCREENH<667){// 4s 4 5s 5
        ratio = SCREENH/667.0;
        self.phoneTopConst.constant = ratio * topConstant;
        
        deviation = self.otherWayTopConst.constant;
        self.otherWayTopConst.constant = ratio * deviation;
        
        deviation -= self.otherWayTopConst.constant;
        deviation += topConstant - self.phoneTopConst.constant;
    }
    
    [self initTencent];
    
    _oauthView = [[YSOauthLoginViewContainer alloc]init];
    UIImage *loginImg = [UIImage imageNamed:@"icon_qq"];
    [_oauthView setY:CGRectGetMaxY(self.otherWayLoginLabel.frame)+ 50*ratio - deviation];
    [_oauthView setX:(SCREENW-(loginImg.size.width*3+34*2))/2];
    [_oauthView.qqLoginBtn addTarget:self action:@selector(tapOauthLoginBtn:) forControlEvents:UIControlEventTouchUpInside];
    [_oauthView.wxLoginBtn addTarget:self action:@selector(tapOauthLoginBtn:) forControlEvents:UIControlEventTouchUpInside];
    [_oauthView.wbLoginBtn addTarget:self action:@selector(tapOauthLoginBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.containView addSubview:_oauthView];

    self.containViewHeightConst.constant += _oauthView.height + 50*ratio - deviation ;
    
    [self initOauthIsEnable];
    
//    [UIUtil dealPlaceHolderColor:self.phoneTextFiled color:[UIColor whiteColor]];
//    [UIUtil dealPlaceHolderColor:self.pwdTextFiled color:[UIColor whiteColor]];
  
    [[NSNotificationCenter defaultCenter] addObserver: self selector:@selector(oauthLoginCallBack:)name:kOauthLoginNortif object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(back:) name:kUpdateMineInfoNortif object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(backFromBindPhone:) name:kUpdatePhoneCodeNortif object:nil];
    
    self.phoneTextFiled.tintColor = ThemeColor;
    self.pwdTextFiled.tintColor = ThemeColor;
}

-(void)initOauthIsEnable{
    
    if(![WXApi isWXAppInstalled]&&![TencentOAuth iphoneQQInstalled]&&![WeiboSDK isWeiboAppInstalled]){
        [self.bgLoginLineLeft setHidden:YES];
        [self.bgLoginLineRight setHidden:YES];
        [self.otherWayLoginLabel setHidden:YES];
        [self.oauthView setHidden:YES];
    }
}

-(BOOL)shouldStatusBarLightContent{
    return NO;
}

-(void)back:(NSNotification *)nortif{
    [self.navigationController dismissViewControllerAnimated:NO completion:nil];
}

-(void)backFromBindPhone:(NSNotification *)nortif{
    NSNumber *number = nortif.object;
    if (number.boolValue) {
        [self updateCartIndex];
        [[NSNotificationCenter defaultCenter]postNotificationName:kUpdateMineInfoNortif object:nil];
    }else{
        [Utils clearExitInfo];
    }
}

-(void)initTencent{
    _tencentOAuth = [[TencentOAuth alloc]initWithAppId:kQQAppId andDelegate:self];
    _permission = [NSArray arrayWithObjects:kOPEN_PERMISSION_GET_INFO,kOPEN_PERMISSION_GET_USER_INFO,kOPEN_PERMISSION_GET_SIMPLE_USER_INFO, nil];
}

- (IBAction)tapAction:(id)sender {
    [self.view endEditing:YES];
}

- (IBAction)tapSender:(UIButton *)sender {
    switch (sender.tag) {
        case 0://返回
            [self back:nil];
            break;
        case 1://登陆title
            NSLog(@"登陆title");
            break;
        case 2://注册
            [self.navigationController pushViewController:[YSRegisterCtrl new] animated:YES];
            break;
        case 3:{//确定
            
            if(ISBLANK(self.phoneTextFiled.text)){
                ShowTips(@"手机号为空");
                return;
            }
            
            if(ISBLANK(self.pwdTextFiled.text)){
                ShowTips(@"验证码为空");
                return;
            }
            
            if(!self.phoneTextFiled.text.isValidatePhone){
                ShowTips(@"非法手机号");
                return;
            }
            
            [YSMineDataTool loginWithParams:self.phoneTextFiled.text validateCode:self.pwdTextFiled.text success:^(YSRegisterRes *result) {
                if(result.isSucc){
                    [result saveInfo];
                    [result saveUserInfo];
                    [self updateCartIndex];
                    [[NSNotificationCenter defaultCenter]postNotificationName:kUpdateMineInfoNortif object:nil];
                    [self back:nil];
                }else{
                   ShowEnterTips(result.data);
                }
            } failure:^(NSError *error) {
                ShowTips(kRequestFailure);
            }];
            break;
        }
        case 4://忘记密码
            [self.navigationController pushViewController:[YSForgetPwdCtrl new] animated:YES];
            break;
        case 5:{// 获取验证码
            if(ISBLANK(self.phoneTextFiled.text)){
                ShowTips(@"手机号为空");
                return;
            }
            [YSMineDataTool sendCodeWithParams:self.phoneTextFiled.text type:0 success:^(BaseResponse *result) {
                if(result.isSucc){
                    [self startCountDown];
                }else{
                    ShowEnterTips(result.data);
                }
            } failure:^(NSError *error) {
                ShowTips(kRequestFailure);
            }];
            break;
        }
        default:
            break;
    }
}

- (void)startCountDown {
    //处理倒计时
    NSString* time_str = [NSString stringWithFormat:@"%ds",self.currentTime];
    _countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:_countDownTimer forMode:NSDefaultRunLoopMode];
    [_sendCodeBtn setEnabled:NO];
    [_sendCodeBtn setTitle:time_str forState:UIControlStateDisabled];
}

-(void)timeFireMethod{
    if(self.currentTime <= 0){
        [_countDownTimer invalidate];
        [_sendCodeBtn setEnabled:YES];
        [_sendCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        self.currentTime = 60;
    }else{
        self.currentTime--;
        NSString *timeStr = [NSString stringWithFormat:@"%ds",self.currentTime];
        [_sendCodeBtn setTitle:timeStr forState:UIControlStateDisabled];
    }
}

-(void)tapOauthLoginBtn:(UIButton *)sender{
    switch (sender.tag) {
        case 5:{//qq
            if ([TencentOAuth iphoneQQInstalled]) {
                if(![_tencentOAuth isSessionValid]){//2.登录时，调用TencetnOAuth对象的authorize方法：
                    [_tencentOAuth authorize:_permission inSafari:NO];
                }
            }
            break;
        }
        case 6://weixin
            if ([WXApi isWXAppInstalled]) {
                [WeChatUtil sendAuthRequest];
            }
            break;
        case 7:{//weibo
            [[SinaClient ShareSinaClient] weiboBind];
            [SinaClient ShareSinaClient].sinaHandler = ^(id sender1,id sender2){
                NSLog(@"sinaLoginClickcallback");
            };
            break;
        }
            
        default:
            break;
    }
}

-(void)updateCartIndex{
    //更新购物篮角标
    if(ISLOGIN){
        [[YSCommonReqTool sharedTool] loadIndex:YSBadgeCartType callback:^(NSInteger count) {
        }];
    }else{
        [DefaultsHelper setInteger:0 forKey:kCartIndex];
    }
}

/**
 *  第三方登录回调
 */
-(void)oauthLoginCallBack:(NSNotification*)aNotification
{
    WeChatUserinfoRes *loginRes = [aNotification object];
    BaseRequest *request = [BaseRequest param];
    NSDictionary *dic = [request keyValues];
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:dic];
    [params setObject:loginRes.unionid forKey:@"unionid"];
    [params setObject:loginRes.nickname forKey:@"nickName"];
    [params setObject:[NSString stringWithFormat:@"%ld",(long)loginRes.sex] forKey:@"userGender"];
    [params setObject:loginRes.headimgurl forKey:@"userImg"];
    [params setObject:loginRes.clientType forKey:@"clientType"];
    [YSMineDataTool oauthLoginWithParam:params success:^(YSRegisterRes *result) {
        if(result.isSucc){//第三方登录成功
            //退出qq
            [_tencentOAuth logout:self];
            [result saveInfo];
            [result saveUserInfo];
            if (ISBLANK(result.phoneCode)) {
                CustomNavigationCtrl *ctrl = [[CustomNavigationCtrl alloc] initWithRootViewController:[[YSBindPhoneCtrl alloc] init]];
                [self presentViewController:ctrl animated:YES completion:nil];
            }else{
                [[NSNotificationCenter defaultCenter] postNotificationName:kUpdateMineInfoNortif object:nil];
            }
        }else{
            ShowEnterTips(result.data);
        }
    } failure:^(NSError *error) {
        ShowTips(kRequestFailure);
    }];
    
    NSLog(@"第三方登录返回%@",loginRes);
}


//----------------qq login start------------------
-(void)getUserInfoResponse:(APIResponse *)response{//获取用户信息成功的回调
    NSString* nickname = [response.jsonResponse objectForKey:@"nickname"];
    NSString* gender = [response.jsonResponse objectForKey:@"gender"];
    NSString* headImg = [response.jsonResponse objectForKey:@"figureurl_qq_1"];
    WeChatUserinfoRes *result = [[WeChatUserinfoRes alloc]init];
    [result setUnionid:[_tencentOAuth openId]];
    [result setClientType:@"1"];
    [result setNickname:nickname];
    [result setHeadimgurl:headImg];
    if([gender isEqualToString:@"男"]){
        [result setSex:1];
    }else{
        [result setSex:2];
    }
    //把获取到的信息传输到登录回调请求服务器进行第三方登录
    [[NSNotificationCenter defaultCenter] postNotificationName:kOauthLoginNortif object:result];
    
    NSLog(@"qqlogin nickname = %@",nickname);
}

-(void)tencentDidLogin{//2. 登录完成后，会调用TencentSessionDelegate中关于登录的协议方法。
    
    if (_tencentOAuth.accessToken && 0 != [_tencentOAuth.accessToken length]){  // 登录成功：记录登录用户的OpenID、Token以及过期时间
        //3. 登录成功后，即可获取到access token和openid。accessToken和 openid保存在TencentOAuth对象中。可以通过相应的属性方法直接获得。
        NSString *qqAccessToken = [_tencentOAuth accessToken];
        NSString *qqOpenId = [_tencentOAuth openId];
        NSDate *qqExpirationDate = [_tencentOAuth expirationDate] ;
        NSLog(@"token = %@,openid = %@,date = %@",qqAccessToken,qqOpenId,qqExpirationDate);
        BOOL result = [_tencentOAuth getUserInfo];
        if(result){
            NSLog(@"获取用户信息成功");
        }else{
            NSLog(@"获取用户信息失败");
        }
    }else{
        //登录不成功 没有获取accesstoken
        ShowTips(@"授权登录失败");
    }
}

-(void)tencentDidNotLogin:(BOOL)cancelled{
    if (cancelled){
        //用户取消登录
        ShowTips(@"授权登录取消");
    }else{
        //登录失败
        ShowTips(@"授权登录失败");
    }
}

-(void)tencentDidNotNetWork{
    //无网络连接，请设置网络
    ShowTips(@"无网络连接");
}

//----------------qq login end------------------
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    NSString *phone =   [DefaultsHelper stringForKey:kUserPhone];
    [self.phoneTextFiled setText:phone];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    _countDownTimer = nil;
}

@end
